package org.shangrila.comm.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class FileUtil {

	public static boolean createFile(String destFileName) {
		File file = new File(destFileName);
		if (file.exists()) {
			System.out.println("创建单个文件" + destFileName + "失败，目标文件已存在！");
			return false;
		}
		if (destFileName.endsWith(File.separator)) {
			System.out.println("创建单个文件" + destFileName + "失败，目标文件不能为目录！");
			return false;
		}
		// 判断目标文件所在的目录是否存在
		if (!file.getParentFile().exists()) {
			// 如果目标文件所在的目录不存在，则创建父目录
			System.out.println("目标文件所在目录不存在，准备创建它！");
			if (!file.getParentFile().mkdirs()) {
				System.out.println("创建目标文件所在目录失败！");
				return false;
			}
		}
		// 创建目标文件
		try {
			if (file.createNewFile()) {
				System.out.println("创建单个文件" + destFileName + "成功！");
				return true;
			} else {
				System.out.println("创建单个文件" + destFileName + "失败！");
				return false;
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.out
					.println("创建单个文件" + destFileName + "失败！" + e.getMessage());
			return false;
		}
	}

	public static boolean createDir(String destDirName) {
		File dir = new File(destDirName);
		if (dir.exists()) {
			System.out.println("创建目录" + destDirName + "失败，目标目录已经存在");
			return false;
		}
		if (!destDirName.endsWith(File.separator)) {
			destDirName = destDirName + File.separator;
		}
		// 创建目录
		if (dir.mkdirs()) {
			System.out.println("创建目录" + destDirName + "成功！");
			return true;
		} else {
			System.out.println("创建目录" + destDirName + "失败！");
			return false;
		}
	}

	public static String createTempFile(String prefix, String suffix,
			String dirName) {
		File tempFile = null;
		if (dirName == null) {
			try {
				// 在默认文件夹下创建临时文件
				tempFile = File.createTempFile(prefix, suffix);
				// 返回临时文件的路径
				return tempFile.getCanonicalPath();
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("创建临时文件失败！" + e.getMessage());
				return null;
			}
		} else {
			File dir = new File(dirName);
			// 如果临时文件所在目录不存在，首先创建
			if (!dir.exists()) {
				if (!FileUtil.createDir(dirName)) {
					System.out.println("创建临时文件失败，不能创建临时文件所在的目录！");
					return null;
				}
			}
			try {
				// 在指定目录下创建临时文件
				tempFile = File.createTempFile(prefix, suffix, dir);
				return tempFile.getCanonicalPath();
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("创建临时文件失败！" + e.getMessage());
				return null;
			}
		}
	}

	// 只读取参数路径下的目录或者文件
	public static void listFilesAndDirs(String path) {
		File dir = new File(path);
		File[] files = dir.listFiles();
		for (int i = 0; i < files.length; i++) {
			System.out.println((files[i].isDirectory() ? "目录：" : "文件：")
					+ files[i].getName());
		}
	}

	// 只读取参数路径下的文件
	public static List<String> listPathFiles(String path) {
		List<String> list = new ArrayList<String>();
		File dir = new File(path);
		File[] files = dir.listFiles();
		if (files.length <= 0)
			return null;
		for (File file : files) {
			if (file.isFile()) {
				// System.out.println(file.getPath()+"--"+file.getName());
				list.add(file.getName());
			}
		}
		return list;
	}

	// 只读取参数路径下的文件
	public static Map<String, String> listPathFile(String path) {
		Map<String, String> map = new HashMap<String, String>();
		File dir = new File(path);
		File[] files = dir.listFiles();
		if (files.length <= 0)
			return null;
		for (File file : files) {
			if (file.isFile()) {
				// System.out.println(file.getPath());
				map.put(file.getPath(), file.getName());
			}
		}
		return map;
	}

	// 递归法读取参数路径下的所有文件
	@SuppressWarnings("unused")
	private static void listFilesRecursion(String path) {
		File f = new File(path);
		File[] fs = f.listFiles();
		if (fs == null) {
			return;
		}
		for (File file : fs) {
			if (file.isFile()) {
				System.out.println(file.getPath());
			} else {
				listFilesRecursion(file.getPath());
			}
		}
	}

	/**
	 * 获取文件扩展名
	 * 
	 * @param file
	 * @return
	 */
	public static String getFileExtension(File file) {
		String fileName = file.getName();
		if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
			return fileName.substring(fileName.lastIndexOf(".") + 1);
		} else {
			return "";
		}
		// System.IO.Path.GetExtension(path);
	}

	public static byte[] getBytesFromFile(String filename) throws IOException {
		File file = new File(filename);
		if ((file.exists()) && (!file.isDirectory()) && (file.length() > 0L)
				&& (file.length() < 10485760L)) {
			byte[] ret = new byte[(int) file.length()];
			@SuppressWarnings("resource")
			FileInputStream fis = new FileInputStream(filename);
			fis.read(ret);
			return ret;
		}
		return null;
	}

	@SuppressWarnings("resource")
	public static String getStringFromFile(String filename) throws IOException {
		FileInputStream fis = new FileInputStream(filename);
		byte[] buffer = new byte[1000];
		StringBuffer sb = new StringBuffer();
		int len = 0;
		while ((len = fis.read(buffer)) > -1) {
			sb.append(new String(buffer, 0, len));
		}
		return sb.toString();
	}

	public static String getStringFromResource(Class<?> clazz, String rname)
			throws IOException, ClassNotFoundException {
		InputStream is = clazz.getResourceAsStream(rname);
		byte[] buffer = new byte[1000];
		StringBuffer sb = new StringBuffer();
		int len = 0;
		while ((len = is.read(buffer)) > -1) {
			sb.append(new String(buffer, 0, len));
		}
		return sb.toString();
	}

	public static String getStringFromResource(String rname)
			throws IOException, ClassNotFoundException {
		InputStream is = FileUtil.class.getResourceAsStream(rname);
		byte[] buffer = new byte[1000];
		StringBuffer sb = new StringBuffer();
		int len = 0;
		while ((len = is.read(buffer)) > -1) {
			sb.append(new String(buffer, 0, len));
		}
		return sb.toString();
	}

	@SuppressWarnings("resource")
	public static String appendTextFile(String filename, String fileinfo) {
		String ret = "success " + filename;
		try {
			FileOutputStream fos = new FileOutputStream(filename, true);
			fos.write(fileinfo.getBytes());
			ret = ret + " " + fileinfo.getBytes().length;
		} catch (IOException e) {
			ret = "fail " + e.getLocalizedMessage();
		}
		return ret;
	}

	@SuppressWarnings("resource")
	public static String writeTextFile(String filename, String fileinfo,
			String charset) {
		String ret = "success " + filename;
		try {
			FileOutputStream fos = new FileOutputStream(filename);
			fos.write(fileinfo.getBytes(charset));
			ret = ret + " " + fileinfo.getBytes().length;
		} catch (IOException e) {
			ret = "fail " + e.getLocalizedMessage();
		}
		return ret;
	}

	public static int getTotalLines(String fileName) {
		FileInputStream fis = null;
		int count;
		try {
			byte[] buf = new byte[10240];
			fis = new FileInputStream(fileName);
			count = 0;
			int lines = 0;
			int i;
			while ((count = fis.read(buf)) != -1) {
				for (i = 0; i < count; i++)
					if (buf[i] == 10)
						lines++;
			}
			fis.close();
			fis = null;
			return lines + 1;
		} catch (Exception ex) {

			return -1;
		} finally {
			try {
				if (fis != null)
					fis.close();
			} catch (Exception localException3) {
			}
		}
	}

	public static String writeTextFile(String filename, String fileinfo) {
		String ret = "success " + filename;
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(filename);
			fos.write(fileinfo.getBytes());
			ret = ret + " " + fileinfo.getBytes().length;
		} catch (IOException e) {
			ret = "fail " + e.getLocalizedMessage();
		} finally {
			try {
				if (fos != null) {
					fos.flush();
					fos.close();
				}
			} catch (Exception localException2) {
			}

		}
		return ret;
	}

	public static String writeBinaryFile(String filename, byte[] fileinfo) {
		String ret = "success " + filename;
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(filename);
			fos.write(fileinfo);
			ret = ret + " " + fileinfo.length;
		} catch (IOException e) {
			ret = "fail " + e.getLocalizedMessage();
		} finally {
			try {
				if (fos != null) {
					fos.flush();
					fos.close();
				}
			} catch (Exception localException2) {
			}

		}
		return ret;
	}

	public static HashMap<String, String> getConfig(Class<?> clazz,
			String configfile) {
		return getConfig(clazz, configfile, "utf-8");
	}

	public static HashMap<String, String> getConfig(Class<?> clazz,
			String configfile, String charset) {
		try {
			Properties loginParas = new Properties();
			InputStream inputStream = clazz.getResourceAsStream(configfile);
			BufferedReader bf = new BufferedReader(new InputStreamReader(
					inputStream, charset));
			loginParas.load(bf);
			Iterator<?> iter = loginParas.stringPropertyNames().iterator();
			HashMap<String, String> ret = new HashMap<String, String>();
			while (iter.hasNext()) {
				String key = (String) iter.next();
				ret.put(key, loginParas.getProperty(key));
			}
			return ret;
		} catch (IOException e) {
		}
		return null;
	}

	public static HashMap<String, String> getConfig(String configfilepath) {
		return getConfig(configfilepath, "utf-8");
	}

	public static HashMap<String, String> getConfig(String configfilepath,
			String charset) {
		try {
			Properties loginParas = new Properties();
			loginParas.load(new InputStreamReader(new FileInputStream(
					configfilepath), charset));
			Iterator<?> iter = loginParas.stringPropertyNames().iterator();
			HashMap<String, String> ret = new HashMap<String, String>();
			while (iter.hasNext()) {
				String key = (String) iter.next();
				ret.put(key, loginParas.getProperty(key));
			}
			return ret;
		} catch (IOException e) {
		}
		return null;
	}

	public static void main(String[] args) {
		// 创建目录
		String dirName = "D:/ttt/temp/temp0/temp1";
		FileUtil.createDir(dirName);
		// 创建文件
		String fileName = dirName + "/temp2/tempFile.txt";
		FileUtil.createFile(fileName);
		// 创建临时文件
		String prefix = "temp";
		String suffix = ".txt";
		for (int i = 0; i < 3; i++) {
			System.out.println("创建了临时文件："
					+ FileUtil.createTempFile(prefix, suffix, dirName));
		}
		// 在默认目录下创建临时文件
		for (int i = 0; i < 3; i++) {
			System.out.println("在默认目录下创建了临时文件："
					+ FileUtil.createTempFile(prefix, suffix, null));
		}
	}
}